package com.smile.service.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smile.api.UserApi;
import com.smile.mapper.AirportMapper;
import com.smile.mapper.DroneMapper;
import com.smile.mapper.OrganizationMapper;
import com.smile.model.domain.FeisuanAirport;
import com.smile.model.domain.FeisuanDrone;
import com.smile.model.domain.SmilePlusOrganization;
import com.smile.service.config.mqtt.handler.AbstractAirportBindStatusHandler;
import com.smile.service.entity.organization.AirportBindStatusData;
import com.smile.service.entity.organization.AirportBindStatusDetailedData;
import com.smile.service.entity.response.DeviceConfigResponse;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DefaultAirportBindStatusHandler extends AbstractAirportBindStatusHandler {
    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private UserApi userApi;

    @Override
    public Boolean process(String data, String bid, String tid,String gateway) throws MqttException {
        JSONObject jsonObject = JSONObject.parseObject(data);
        AirportBindStatusData airportBindStatusData = jsonObject.toJavaObject(AirportBindStatusData.class);

        List<Map<String, Object>> list = (List<Map<String, Object>>)jsonObject.get("devices");

        List<AirportBindStatusDetailedData.DeviceBindStatus> devices =
                new ArrayList<>();

        for (Map<String, Object> map : list) {
            AirportBindStatusDetailedData.DeviceBindStatus deviceBindStatus = new AirportBindStatusDetailedData.DeviceBindStatus();
            System.out.println(map.get("sn"));
            System.out.println(gateway);
            if(map.get("sn").toString().equals(gateway)){//和机场相同则为机场
                QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("gateway_sn",map.get("sn"));
                FeisuanAirport feisuanAirport = airportMapper.selectOne(queryWrapper);
                System.out.println(feisuanAirport);
                if(ObjectUtil.isNotNull(feisuanAirport)){
                    SmilePlusOrganization organization = organizationMapper.selectById(feisuanAirport.getOrganizationId());

                    deviceBindStatus.setSerialNumber(feisuanAirport.getGatewaySn());
                    deviceBindStatus.setOrganizationId(organization.getOrganizationCode());
                    deviceBindStatus.setDeviceBoundToOrganization(Boolean.TRUE);
                    deviceBindStatus.setOrganizationName(organization.getOrganizationName());
                    deviceBindStatus.setDeviceCallsign(feisuanAirport.getAirportName() );
                    devices.add(deviceBindStatus);
                }
            }else{

                QueryWrapper<FeisuanDrone> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("drone_sn",map.get("sn"));
                FeisuanDrone feisuanDrone = droneMapper.selectOne(queryWrapper);
                if(ObjectUtil.isNotNull(feisuanDrone)){
                    SmilePlusOrganization organization = organizationMapper.selectById(feisuanDrone.getOrganizationId());
                    deviceBindStatus.setSerialNumber(feisuanDrone.getDroneSn());
                    deviceBindStatus.setOrganizationId(organization.getOrganizationCode());
                    deviceBindStatus.setDeviceBoundToOrganization(Boolean.TRUE);
                    deviceBindStatus.setOrganizationName(organization.getOrganizationName() );
                    deviceBindStatus.setDeviceCallsign(feisuanDrone.getDroneName());
                    devices.add(deviceBindStatus);
                }
            }
        }
        //TODO 这里还没有写完
        AirportBindStatusDetailedData airportBindStatusDetailedData = new AirportBindStatusDetailedData();

//                    List<AirportBindStatusDetailedData.DeviceBindStatus> bindStatusList
//                            = new ArrayList<>();
//        AirportBindStatusDetailedData.DeviceBindStatus deviceBindStatus = new AirportBindStatusDetailedData.DeviceBindStatus();


        AirportBindStatusDetailedData.BindStatusOutput bindStatusOutput = new AirportBindStatusDetailedData.BindStatusOutput();






//
//        AirportBindStatusDetailedData.DeviceBindStatus deviceBindStatus1 = new AirportBindStatusDetailedData.DeviceBindStatus();
//        deviceBindStatus1.setSerialNumber("8UUXN2800A00HX");
//        deviceBindStatus1.setOrganizationId("9veeb2");
//        deviceBindStatus1.setDeviceBoundToOrganization(Boolean.TRUE);
//        deviceBindStatus1.setOrganizationName("测试机场");
//        deviceBindStatus1.setDeviceCallsign("测试组织");
//        deviceBindStatus1.setDeviceBoundToOrganization(true);
//        devices.add(deviceBindStatus1);

        bindStatusOutput.setBindStatusList(devices);
        airportBindStatusDetailedData.setOutput(bindStatusOutput);
        airportBindStatusDetailedData.setResultCode(0);

        DeviceConfigResponse<AirportBindStatusDetailedData> deviceConfigResponse = new DeviceConfigResponse<>();
        deviceConfigResponse.setBid(bid);
        deviceConfigResponse.setTid(tid);
        deviceConfigResponse.setData(airportBindStatusDetailedData);
        deviceConfigResponse.setTimestamp(System.currentTimeMillis());
        deviceConfigResponse.setMethod("airport_bind_status");
        deviceConfigResponse.setGateway(gateway);

        log.info("DefaultAirportBindStatusHandler {}", JSONObject.toJSONString(deviceConfigResponse));

        MqttMessage message = new MqttMessage();
        message.setQos(0);
        message.setRetained(true);
        message.setPayload(JSONObject.toJSONString(deviceConfigResponse).getBytes());
        MqttClient mqttClient = new MqttClient("tcp://120.211.119.131:1883", "feisuan-mqtt-producer-client", new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("feisuan");
        connOpts.setPassword("feisuan123456".toCharArray());
        mqttClient.connect(connOpts);

        mqttClient.publish("thing/product/" + gateway + "/requests_reply", message);
//        mqttCli


        return Boolean.TRUE;
    }
}
